package com.itboye.ihomebank.activity.key.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.View;
import android.widget.ListView;

import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.itboye.ihomebank.R;
import com.itboye.ihomebank.adapter.GuanLiPassAdapter;
import com.itboye.ihomebank.base.BaseFragment;
import com.itboye.ihomebank.base.MyApplcation;
import com.itboye.ihomebank.base.ptr.BasePtr;
import com.itboye.ihomebank.bean.GuanLiPassBean;
import com.itboye.ihomebank.bean.ResultEntity;
import com.itboye.ihomebank.bean.SIDBean;
import com.itboye.ihomebank.constants.SPContants;
import com.itboye.ihomebank.interfaces.IRefreshAfterAlert;
import com.itboye.ihomebank.presenter.KeyPresenter;
import com.itboye.ihomebank.presenter.UserPresenter;
import com.itboye.ihomebank.ttKey.DbService;
import com.itboye.ihomebank.ttKey.Key;
import com.itboye.ihomebank.ttKey.MyPreference;
import com.itboye.ihomebank.util.ByAlert;
import com.itboye.ihomebank.util.SPUtils;
import com.itboye.ihomebank.util.UIAlertView;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import in.srain.cube.views.ptr.PtrDefaultHandler2;
import in.srain.cube.views.ptr.PtrFrameLayout;

/**
 * 锁用户管理---密码
 */
public class FragmentGuanLiPass extends BaseFragment implements Observer ,View.OnClickListener, IRefreshAfterAlert {
    ListView listView;
    PtrFrameLayout commend_anchor_ptr;

    UserPresenter userPresenter;
    KeyPresenter keyPresenter;
    private GuanLiPassBean bean;

    List<GuanLiPassBean.Date> beanList;
    GuanLiPassAdapter adapter;

    private String uid;
    public static  String lockId,lockMac;

    int current_page=1;
    int per_page=10;

    private UIAlertView uiAlertView;

    public static boolean addLock = false;
    private int cz;
    @Override
    public int initView() {
        return R.layout.fragment_guan_li_pass;
    }
    @Override
    public void onMyActivityCreated() {
        BasePtr.setPagedPtrStyle(commend_anchor_ptr);//设置上拉下拉刷新
        uid = SPUtils.get(getActivity(), null, SPContants.USER_ID, "") + "";
        lockId = getActivity().getIntent().getStringExtra("lockid");
        lockMac= getActivity().getIntent().getStringExtra("lockMac");
        userPresenter=new UserPresenter(this);
        keyPresenter=new KeyPresenter(this);
        bean=new GuanLiPassBean();
        beanList=new ArrayList<>();
        cz=1;
        String sid=SPUtils.get(MyApplcation.ctx,null,SPContants.LOCK_SESSION,"")+"";
        if ("".equals(sid)){
            userPresenter.passJiLu(uid,lockId,current_page+"",per_page+"");
        }else {
            userPresenter.passJiLu(sid,lockId,current_page+"",per_page+"");
        }


        adapter = new GuanLiPassAdapter(getActivity(), beanList,R.layout.item_yoghu_pass);
        listView.setAdapter(adapter);
        commend_anchor_ptr.setPtrHandler(new PtrDefaultHandler2() {
            @Override
            public void onLoadMoreBegin(PtrFrameLayout frame) {
                String sid=SPUtils.get(MyApplcation.ctx,null,SPContants.LOCK_SESSION,"")+"";
                current_page++;
                if ("".equals(sid)){
                    userPresenter.passJiLu(uid,lockId,current_page+"",per_page+"");

                }else {
                    userPresenter.passJiLu(sid,lockId,current_page+"",per_page+"");

                }
            }
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                String sid=SPUtils.get(MyApplcation.ctx,null,SPContants.LOCK_SESSION,"")+"";
                if ("".equals(sid)){
                    userPresenter.passJiLu(uid,lockId,current_page+"",per_page+"");

                }else {
                    userPresenter.passJiLu(sid,lockId,current_page+"",per_page+"");

                }
            }
        });
       // commend_anchor_ptr.autoRefresh();

        IntentFilter intentFilterAvart = new IntentFilter("suo_ok");// 广播 当收到SDK重置键盘密码成功调用接口，重置键盘密码
        getActivity().registerReceiver(avartBroadcastReceiver,
                intentFilterAvart);

    }
    /**
     * 广播 当收到SDK重置键盘密码成功调用接口，重置键盘密码
     */
    private Key broadKey;
    BroadcastReceiver avartBroadcastReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
          //  closeProgressDialog();
            cz=2;
            String accessToken = MyPreference.getStr(getActivity(), MyPreference.ACCESS_TOKEN);
            broadKey = DbService.getKeyByAccessTokenAndLockmac(accessToken, lockMac);
            String sid=SPUtils.get(MyApplcation.ctx,null,SPContants.LOCK_SESSION,"")+"";

            if ("".equals(sid)){
                keyPresenter.getJianPanPass(SPUtils.get(getActivity(), null, SPContants.USER_ID, "") + "", lockId+"", broadKey.getPwdInfo()
                        + "", broadKey.getTimestamp() + "");
            }else {
                keyPresenter.getJianPanPass(sid, lockId+"", broadKey.getPwdInfo()
                        + "", broadKey.getTimestamp() + "");
            }

        }
    };
    @Override
    public void update(Observable observable, Object data) {
        // TODO Auto-generated method stub
        ResultEntity entity = handlerError(data);
        if (entity != null) {
            if (entity.getEventType() == UserPresenter.pass_jilu_success) {
                if (current_page == 1) {
                    beanList.clear();
                }
                commend_anchor_ptr.refreshComplete();//设置刷新完成
                bean= (GuanLiPassBean) entity.getData();
                if (bean!=null){
                    beanList.addAll(bean.getData());
                    if (beanList.size() > 0) {
                        adapter.notifyDataSetChanged();
                    }
                }
            }
            else if (entity.getEventType() == UserPresenter.pass_jilu_fail) {
                ByAlert.alert(entity.getData());
            }
            //重置密码
            else if (entity.getEventType() == UserPresenter.delete_jianpan_pass_success) {
                ByAlert.alert(entity.getData());
            }
            else if (entity.getEventType() == UserPresenter.delete_jianpan_pass_fail) {
                ByAlert.alert(entity.getData());
            }
            // 重置键盘密码
            else	if (entity.getEventType() == KeyPresenter.jianpanPass_success) {
//                ByAlert.alert(entity.getData());
                try {
                    closeProgressDialog();
                }catch (Exception e){

                }
                beanList=new ArrayList<>();
                adapter = new GuanLiPassAdapter(getActivity(), beanList,R.layout.item_yoghu_pass);
                listView.setAdapter(adapter);
            } else if (entity.getEventType() == KeyPresenter.jianpanPass_fail) {
                ByAlert.alert(entity.getData());
            }else if (entity.getEventType()==UserPresenter.By_GETSID_success){//获取sid 成功
                SIDBean data1 = (SIDBean) entity.getData();
                SPUtils.put(MyApplcation.ctx,null, SPContants.LOCK_SESSION,data1.getSid());
                SPUtils.put(MyApplcation.ctx,null,SPContants.ISLOCK,true);
                toRefreshData();
            }else if (entity.getEventType()==UserPresenter.By_GETSID_fail){
                ByAlert.alert(entity.getMsg());
            }

            //获取备用服务器的session
            if (entity.getData() instanceof ServerError ||entity.getData() instanceof TimeoutError){//服务器失败
                //切换 锁备用服务器
                showAlert();
            }
        }
    }

    @Override
    public void onClick(View v) {

    }

    @Override
    public void toRefreshData() {
        String sid=SPUtils.get(MyApplcation.ctx,null,SPContants.LOCK_SESSION,"")+"";

        if (cz==2){
            if ("".equals(sid)){
                keyPresenter.getJianPanPass(SPUtils.get(getActivity(), null, SPContants.USER_ID, "") + "", lockId+"", broadKey.getPwdInfo()
                        + "", broadKey.getTimestamp() + "");
            }else {
                keyPresenter.getJianPanPass(sid, lockId+"", broadKey.getPwdInfo()
                        + "", broadKey.getTimestamp() + "");
            }
        }else if (cz==1){
            if ("".equals(sid)){
                userPresenter.passJiLu(uid,lockId,current_page+"",per_page+"");

            }else {
                userPresenter.passJiLu(sid,lockId,current_page+"",per_page+"");

            }
        }

    }
}
